package com.army.stock.web;

import com.alibaba.fastjson.JSON;
import com.army.stock.domain.ArmyCategory;
import com.army.stock.domain.ArmyDepartment;
import com.army.stock.domain.ArmyRole;
import com.army.stock.domain.ArmyUser;
import com.army.stock.service.ArmyDepartmentService;
import com.army.stock.service.ArmyRoleService;
import com.army.stock.service.ArmyUserService;
import com.javalife.common.domain.page.PaginatedArrayList;
import com.javalife.common.web.url.BaseUrl;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhangyong on 14/12/29.
 * 权限管理相关
 */
@Controller
public class ArmyPermitionController {

    private final static Logger logger = LoggerFactory.getLogger(ArmyPermitionController.class);

    private final static String UPDATE_PAGE = "user/edit";

    private final static String NEW_PAGE = "user/new";

    private final static String UPDATE_PERMIT_PAGE = "user/updatepermit";

    private final static String UPDATE_ROLE_PERMIT_PAGE = "user/updaterolepermit";

    //修改用户的角色页面
    private final static String UPDATE_USER_ROLE_PERMIT_PAGE = "user/updateUserRole";

    private final static String ROLE_LIST_PAGE = "user/rolelist";

    private final static String ADD_ROLE_PAGE = "user/roleadd";

    private final static String EDIT_ROLE_PAGE = "user/roleedit";

    @Autowired
    private ArmyUserService armyUserService;

    @Autowired
    private ArmyDepartmentService armyDepartmentService;

    @Autowired
    private ArmyRoleService armyRoleService;

    @RequestMapping(value = "/permit/users", method = RequestMethod.GET)
    public String users(HttpServletRequest request, ModelMap modelMap) {
        BaseUrl baseUrl = new BaseUrl(request);
        PaginatedArrayList<ArmyCategory> pageInfo = armyUserService.getArmyUserPageInfo(
                baseUrl.getCurrentPage(),
                10,
                baseUrl.getQueryMap());
        modelMap.put("page", pageInfo);
        modelMap.put("baseUrl", baseUrl);
        return "user/users";
    }

    @RequestMapping(value = "/permit/users/new", method = RequestMethod.GET)
    public String addUserPage(HttpServletRequest request, ModelMap modelMap) {
        List<ArmyDepartment> armyDepartmentList = armyDepartmentService.getAllArmyDepartments();
        modelMap.put("armyDepartmentList", armyDepartmentList);
        return "user/new";
    }

    @RequestMapping(value = "/permit/users/add", method = RequestMethod.POST)
    public String addUser(ArmyUser armyUser, HttpServletRequest request, ModelMap modelMap) {
        logger.info("开始添加用户 {}", armyUser);
        if (armyUser == null) {
            modelMap.put("errorMsg", "参数有问题，请联系开发者!");
            return NEW_PAGE;
        }
        if (StringUtils.isEmpty(armyUser.getUserName())) {
            modelMap.put("errorMsg", "用户名不能为空!");
            return NEW_PAGE;
        }
        if (!armyUser.getUserName().matches("[A-Za-z0-9]+")) {
            modelMap.put("errorMsg", "用户名必须为中英文字符!");
            return NEW_PAGE;
        }
        if (StringUtils.isEmpty(armyUser.getPassword())) {
            modelMap.put("errorMsg", "密码不能为空!");
            return NEW_PAGE;
        }
        if (!StringUtils.equals(armyUser.getPassword(), armyUser.getRepassword())) {
            modelMap.put("errorMsg", "两次输入密码不一致!");
            return NEW_PAGE;
        }
        if (armyUser.getDepartmentId() == null) {
            modelMap.put("errorMsg", "部门编号不能为空!");
            return NEW_PAGE;
        }
        if (StringUtils.isEmpty(armyUser.getRealName())) {
            modelMap.put("errorMsg", "真实姓名不能为空!");
            return NEW_PAGE;
        }
        armyUserService.addArmyUser(armyUser);
        return "redirect:/permit/users";
    }

    @RequestMapping(value = "/permit/users/{userId}/update", method = RequestMethod.GET)
    public String editPage(@PathVariable(value = "userId") String userId, HttpServletRequest request, ModelMap modelMap) {
        modelMap.put("userId", userId);
        List<ArmyDepartment> armyDepartmentList = armyDepartmentService.getAllArmyDepartments();
        modelMap.put("armyDepartmentList", armyDepartmentList);
        ArmyUser armyUser = armyUserService.getArmyUserEntityById(Long.valueOf(userId));
        modelMap.put("armyUser", armyUser);
        return UPDATE_PAGE;
    }

    @RequestMapping(value = "/permit/users/update", method = RequestMethod.POST)
    public String update(ArmyUser armyUser, HttpServletRequest request, ModelMap modelMap) {
        if (armyUser == null) {
            modelMap.put("errorMsg", "参数有问题，请联系开发者!");
            return UPDATE_PAGE;
        }
        if (StringUtils.isEmpty(armyUser.getUserName())) {
            modelMap.put("errorMsg", "用户名不能为空!");
            return UPDATE_PAGE;
        }
        if (!armyUser.getUserName().matches("[A-Za-z0-9]+")) {
            modelMap.put("errorMsg", "用户名必须为中英文字符!");
            return UPDATE_PAGE;
        }
        if (StringUtils.isEmpty(armyUser.getPassword())) {
            modelMap.put("errorMsg", "密码不能为空!");
            return UPDATE_PAGE;
        }
        if (!StringUtils.equals(armyUser.getPassword(), armyUser.getRepassword())) {
            modelMap.put("errorMsg", "两次输入密码不一致!");
            return UPDATE_PAGE;
        }
        if (armyUser.getDepartmentId() == null) {
            modelMap.put("errorMsg", "部门编号不能为空!");
            return UPDATE_PAGE;
        }
        if (StringUtils.isEmpty(armyUser.getRealName())) {
            modelMap.put("errorMsg", "真实姓名不能为空!");
            return UPDATE_PAGE;
        }
        armyUserService.updateArmyUser(armyUser);
        return "redirect:/permit/users";
    }

    @RequestMapping(value = "/permit/users/{userId}/updatepermit", method = RequestMethod.GET)
    public String updatepermitPage(@PathVariable(value = "userId") String userId, HttpServletRequest request, ModelMap modelMap) {
        ArmyUser armyUser = armyUserService.getArmyUserEntityById(Long.valueOf(userId));
        modelMap.put("armyUser", armyUser);
        return UPDATE_PERMIT_PAGE;
    }

    @RequestMapping(value = "/permit/rolelist", method = RequestMethod.GET)
    public String roleList(HttpServletRequest request, ModelMap modelMap) {
        BaseUrl baseUrl = new BaseUrl(request);
        PaginatedArrayList<ArmyCategory> pageInfo = armyRoleService.getArmyRolePageInfo(
                baseUrl.getCurrentPage(),
                10,
                baseUrl.getQueryMap());
        modelMap.put("page", pageInfo);
        modelMap.put("baseUrl", baseUrl);
        return ROLE_LIST_PAGE;
    }

    @RequestMapping(value = "/permit/role/new", method = RequestMethod.GET)
    public String addRolePage(HttpServletRequest request, ModelMap modelMap) {
        return ADD_ROLE_PAGE;
    }

    @RequestMapping(value = "/permit/role/add", method = RequestMethod.POST)
    public String addRolePage(ArmyRole armyRole, HttpServletRequest request, ModelMap modelMap) {
        if (StringUtils.isEmpty(armyRole.getRoleName())) {
            modelMap.put("errorMsg", "角色名称不能为空!");
            return ADD_ROLE_PAGE;
        }
        if (StringUtils.isEmpty(armyRole.getRemark())) {
            modelMap.put("errorMsg", "角色简介不能为空!");
            return ADD_ROLE_PAGE;
        }
        armyRoleService.addArmyRole(armyRole);
        return "redirect:/permit/rolelist";
    }

    @RequestMapping(value = "/permit/rolelist/{roleId}/update", method = RequestMethod.GET)
    public String editRolePage(@PathVariable(value = "roleId") String roleId, HttpServletRequest request, ModelMap modelMap) {
        ArmyRole armyRole = armyRoleService.getArmyRoleById(Long.valueOf(roleId));
        modelMap.put("armyRole", armyRole);
        return EDIT_ROLE_PAGE;
    }

    @RequestMapping(value = "/permit/role/update", method = RequestMethod.POST)
    public String editRole(ArmyRole armyRole, HttpServletRequest request, ModelMap modelMap) {
        if (StringUtils.isEmpty(armyRole.getRoleName())) {
            modelMap.put("errorMsg", "角色名称不能为空!");
            return EDIT_ROLE_PAGE;
        }
        if (StringUtils.isEmpty(armyRole.getRemark())) {
            modelMap.put("errorMsg", "角色简介不能为空!");
            return EDIT_ROLE_PAGE;
        }
        armyRoleService.updateArmyRole(armyRole);
        return "redirect:/permit/rolelist";
    }

    @RequestMapping(value = "/permit/rolelist/{roleId}/updatepermit", method = RequestMethod.GET)
    public String editRolePermitPage(@PathVariable(value = "roleId") String roleId, HttpServletRequest request, ModelMap modelMap) {
        ArmyRole armyRole = armyRoleService.getArmyRoleById(Long.valueOf(roleId));
        modelMap.put("armyRole", armyRole);
        List permits = armyRoleService.getAllPermitsByRoleId(Long.valueOf(roleId));
        String permitsJson = JSON.toJSONString(permits);
        logger.info("permitsJson:{}", permitsJson);
        modelMap.put("armyRole", armyRole);
        modelMap.put("permitsJson", permitsJson);
        return UPDATE_ROLE_PERMIT_PAGE;
    }

    @RequestMapping(value = "/permit/rolelist/updatepermit", method = RequestMethod.POST)
    @ResponseBody
    public String updateRolePermit(HttpServletRequest request, ModelMap modelMap) {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            String roleId = request.getParameter("roleId");
            String permits = request.getParameter("permits");
            armyRoleService.updateRolePermits(roleId, permits);
            returnMap.put("code", "0");
        } catch (Exception e) {
            logger.error("updateRolePermit error:", e);
            returnMap.put("code", "-1");
        }
        return JSON.toJSONString(returnMap);
    }

    @RequestMapping(value = "/permit/users/{userId}/roles", method = RequestMethod.GET)
    public String editUserRolePage(@PathVariable(value = "userId") String userId, HttpServletRequest request, ModelMap modelMap) {
        List<Map> allRoleList = armyRoleService.getAllArmyRoleByUserId(userId);
        modelMap.put("allRoleList", allRoleList);
        modelMap.put("userId", userId);
        return UPDATE_USER_ROLE_PERMIT_PAGE;
    }

    @RequestMapping(value = "/permit/users/updateRole", method = RequestMethod.POST)
    @ResponseBody
    public String updateUserRole(HttpServletRequest request, ModelMap modelMap) {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            String userId = request.getParameter("userId");
            String roleIds = request.getParameter("roleIds");
            armyRoleService.updateUserRole(userId, roleIds);
            returnMap.put("code", "0");
        } catch (Exception e) {
            logger.error("updateRole error:", e);
            returnMap.put("code", "-1");
        }
        return JSON.toJSONString(returnMap);
    }

}
